package com.example.zhaoping.lnterceptor;

import com.example.zhaoping.enums.AppHttpCodeEnum;
import com.example.zhaoping.exception.SystemException;
import com.example.zhaoping.utils.BaseContext;
import com.example.zhaoping.utils.JwtUtils;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j

public class Loginlnterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public Loginlnterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得请求头中的token
        String token = request.getHeader("token");
        String method = request.getMethod();
        // 打印请求路径
        log.info("请求的Request URL: {}", request.getRequestURL());
        if("OPTIONS".equals(method)) {
            return true;

        }
        if (StrUtil.isBlank(token)){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);


        }

        Claims claims = JwtUtils.parseJWT(token);
        Integer useridInt = claims.get("userid", Integer.class);
        Long userid = useridInt.longValue();
        //用token获取redis中的用户
        String s = stringRedisTemplate.opsForValue().get("login:" + useridInt);
        if (StrUtil.isBlank(s)){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
//        存放threadlocal
        BaseContext.setCurrentId(userid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    BaseContext.removeUser();
    }
}
